package hu.bme.mit.inf.seample.gen.util;

import hu.bme.mit.inf.seample.gen.ProjectNameNotSettedException;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;

public class CopyRestJars {

	private static final String JAXRS_API_JAR = "jaxrs-api.jar";
	private static final String JBOSS_SEAM_RESTEASY_JAR = "jboss-seam-resteasy.jar";
	private static final String RESTEASY_JAXB_PROVIDER_JAR = "resteasy-jaxb-provider.jar";
	private static final String RESTEASY_JAXRS_JAR = "resteasy-jaxrs.jar";
	
	private static final URL JAXRS_API = CopyRestJars.class.getResource(JAXRS_API_JAR);
	private static final URL JBOSS_SEAM_RESTEASY = CopyRestJars.class.getResource(JBOSS_SEAM_RESTEASY_JAR);
	private static final URL RESTEASY_JAXB_PROVIDER = CopyRestJars.class.getResource(RESTEASY_JAXB_PROVIDER_JAR);
	private static final URL RESTEASY_JAXRS = CopyRestJars.class.getResource(RESTEASY_JAXRS_JAR);
	private static final List<URL> jars = new ArrayList<URL>();
	private static List<String> jarnames = new ArrayList<String>();
	
	static {
		jars.add(JAXRS_API);
		jars.add(JBOSS_SEAM_RESTEASY);
		jars.add(RESTEASY_JAXB_PROVIDER);
		jars.add(RESTEASY_JAXRS);
		jarnames .add(JAXRS_API_JAR);
		jarnames.add(JBOSS_SEAM_RESTEASY_JAR);
		jarnames.add(RESTEASY_JAXB_PROVIDER_JAR);
		jarnames.add(RESTEASY_JAXRS_JAR);
	}
	
	public void copyToLib(String projectName) throws ProjectNameNotSettedException, CoreException, IOException {
		if (projectName == null || projectName.isEmpty()) {
			throw new ProjectNameNotSettedException();
		}
		IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
		if (p != null) {
			IFolder earContent = p.getFolder("EarContent");
			if (!earContent.exists())
				earContent.create(true, true, null);
			IFolder f = earContent.getFolder("lib");
			if (!f.exists())
				f.create(true, true, null);
			copyTo(f);
		}
	}
	
	private void copyTo(IFolder folder) throws ProjectNameNotSettedException, IOException, CoreException {
		for (URL u : jars) {
			InputStream stream = u.openStream();
			String name = null;
			for (String n : jarnames) {
				if (u.getFile().contains(n)) {
					name = n;
				}
			}
			if (name == null)
				return;
			IFile file = folder.getFile(name);
			if (!file.exists()) {
				file.create(stream, IResource.BACKGROUND_REFRESH, null);
			}
		}
	}
	
}
